#!/usr/bin/python2.4
#
#Copyright 2009 Google Inc.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#


"""Tests for the module tree_node."""

import logging
import unittest
import db_utils
from metadata_handler import UploadMetadataHandler
from metadata_in_memory import  MetadataInMemory
from page_tree_creator import PageTreeCreator
from sorting_column_sets import SetManager
import text_data_reader
from tree_node import PageTree


class Request(object):
  """Dummy Request class."""
  uri = ''
  url = ''
  path = ''
  version_id = None

  def SetVersionId(self, version_id):
    """Dummy set version id method.

    Args:
      version_id: Version id number.
    """
    self.version_id = version_id

  def get(self, param):
    """Dummy get method which returns version_id parameter.

    Args:
      param: Paramter name string.
    Returns:
      Paramter value string.
    """
    if param == 'version_id':
      return self.version_id


class Response(object):
  """Dummy Response class."""

  class Out(object):
    """Dummy Out class for the Response object."""
    text = ''

    def write(self, st):
      """Dummy write response method.

      Args:
        st: String html response.
      """
      self.text = st

  def set_status(self, code):
    """Dummy set status code method.

    Args:
      code: Status code number.
    """
    self.status_code = code

  def clear(self):
    """Dummy clear method."""
    pass
  status_code = ''
  out = Out()


class TreeNodeTest(unittest.TestCase):
  """Tests tree_node module."""

  def setUp(self):
    """Set up method."""
    logging.info('TEST: ' + self.id())
    self.db_handler = db_utils.DbHandler()
    self.metadata_in_memory = MetadataInMemory()
    self.page_tree = PageTree()
    self.set_manager = SetManager()
    self.set_manager.Clear()

  def tearDown(self):
    self.set_manager.Clear()

  def PrepareDb(self, version_id):
    """Write metadata into db.

    Args:
      version_id: Version id number.
    """
    f = open('test/data/metadata_valid.txt', 'r')
    text_data_reader.ReadMetadataFile(f, version_id)
    f.close()
    self.metadata_in_memory.UpdateMetadata({}, {}, {})
    self.upload_metadata_handler = UploadMetadataHandler()
    self.upload_metadata_handler.request = Request()
    self.upload_metadata_handler.request.uri = 'http://localhost:8080'
    self.upload_metadata_handler.response = Response()
    self.upload_metadata_handler.get()
    while True:
      out_text = self.upload_metadata_handler.response.out.text
      if out_text.find('/uploadmetadata') != -1:
        self.upload_metadata_handler = UploadMetadataHandler()
        self.upload_metadata_handler.request = Request()
        self.upload_metadata_handler.request.uri = 'http://localhost:8080'
        self.upload_metadata_handler.response = Response()
        self.upload_metadata_handler.get()
      else:
        return

  def PrepareTree(self, version_id):
    """Generate PageTree.

    Args:
      version_id: Version id number.
    """
    f = open('test/data/global_valid.txt', 'r')
    text_data_reader.GetGlobalData(f, version_id)
    f.close()
    self.page_tree_creator = PageTreeCreator()
    self.page_tree_creator.current_version_id = version_id
    self.page_tree_creator.urls = []
    if self.set_manager.IsSetEmpty(3):
      self.page_tree_creator.no_of_levels = 2
    else:
      self.page_tree_creator.no_of_levels = 3
    self.page_tree_creator.CreatePageTree()

  def testCreateNodes(self):
    """Tests the method CreateNodes."""
    version_id = self.db_handler.CreateNewVersion()
    self.PrepareDb(version_id)
    self.PrepareTree(version_id)

    f = open('test/data/metadata_valid.txt', 'r')
    f.readline()
    f.readline()
    f.readline()
    for line in f:
      columns = text_data_reader.ReadLine(line)
      node = self.page_tree.GetNode(columns[0])
      self.assertEqual(node.key, columns[0])
      self.assert_(node.leaf_node)
      p1 = self.page_tree.GetNode(node.GetParent())
      self.assert_(node.key in p1.GetChildren())
      self.assertEqual(p1.value, columns[2])
      p2 = self.page_tree.GetNode(p1.GetParent())
      self.assert_(p1.key in p2.GetChildren())
      self.assertEqual(p2.value, columns[1])
      p3 = self.page_tree.GetNode(p2.GetParent())
      self.assert_(p2.key in p3.GetChildren())
      self.assertEqual(p3.key, 'ROOT')
      self.assertEqual(p3.value, 'Home')
    f.close()
    self.page_tree.Clear()
    self.metadata_in_memory.Clear()
    self.db_handler.RemoveVersion(version_id)


def main(unused_argv):
  unittest.main()
